//
//  ARPersonalPageController.swift
//  AquaRaft
//
//  Created by 何启亮 on 2024/4/22.
//

import UIKit
import SnapKit

class ARPersonalPageController: ARBaseViewController {

    // MARK: - Property
    
    let userId: String
    let viewModel: ARPersonalPageViewModel
    
    // MARK: - Init
    
    init(userId: String) {
        self.userId = userId
        self.viewModel = ARPersonalPageViewModel(userId: userId)
        
        super.init(nibName: nil, bundle: nil)
        
        self.fd_prefersNavigationBarHidden = true
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    // MARK: -
    
    override func viewDidLoad() {
        super.viewDidLoad()

        setupUI()
        refreshData()
    }
    
    // MARK: - UI
    
    private func setupUI() {
        
        self.view.addSubview(bgView)
        self.view.addSubview(backBtn)
        self.view.addSubview(moreBtn)
        self.view.addSubview(avatarBtn)
        self.view.addSubview(followBtn)
        self.view.addSubview(nicknameLabel)
        self.view.addSubview(giftNumView)
        self.addChild(self.workController)
        self.view.addSubview(self.workController.view)
        
        bgView.snp.makeConstraints { make in
            make.left.right.top.equalToSuperview()
            // 高度自适应
        }
        
        backBtn.snp.makeConstraints { make in
            make.left.equalToSuperview().offset(20)
            make.top.equalToSuperview().offset(8 + ARHelper.statusBarHeight())
            make.width.height.equalTo(28)
        }
        
        moreBtn.snp.makeConstraints { make in
            make.width.height.equalTo(30)
            make.right.equalToSuperview().offset(-20)
            make.centerY.equalTo(backBtn)
        }
        
        avatarBtn.snp.makeConstraints { make in
            make.width.height.equalTo(88)
            make.left.equalToSuperview().offset(20)
            make.top.equalTo(backBtn.snp.bottom).offset(30)
        }
        
        followBtn.snp.makeConstraints { make in
            make.width.height.equalTo(24)
            make.right.equalTo(avatarBtn).offset(-3)
            make.bottom.equalTo(avatarBtn)
        }
        
        nicknameLabel.snp.makeConstraints { make in
            make.left.equalTo(avatarBtn.snp.right).offset(16)
            make.right.equalToSuperview().offset(-20)
            make.centerY.equalTo(avatarBtn)
        }
        
        giftNumView.snp.makeConstraints { make in
            make.centerX.equalToSuperview()
            make.bottom.equalTo(bgView).offset(10)
        }
        
        workController.view.snp.makeConstraints { make in
            make.left.right.equalToSuperview()
            make.bottom.equalToSuperview().offset(-ARHelper.safeBottomHeight())
            make.top.equalTo(giftNumView.snp.bottom).offset(16)
        }
    }
    
    // MARK: - Action
    
    @objc private func moreBtnCliked(_ sender: UIButton) {
        guard let user = viewModel.userModel else {
            return
        }
        ARUserRelationshipHelper.workMoreAction(user: user, vc: self) { [weak self] type, err in
            if let err = err {
                self?.ar.makeToast(err.localizedDescription)
                return
            }
            switch type {
            case .blackList:
                // 黑名单 - 返回
                self?.ar_transitionToBack()
            case .follow:
                // 成功 - 更新cell
                self?.updateVcValue()
            }
        }
    }
    
    @objc private func followBtnClicked(_ sender: UIButton) {
        self.ar.showLoading()
        viewModel.followUser { [weak self] err in
            self?.ar.hideHUD()
            if let err = err {
                self?.ar.makeToast(err.localizedDescription)
                return
            }
            
            // 刷新一下
            self?.ar.makeToast(ARHelper.localString("Follow Successfully"))
            self?.updateVcValue()
        }
    }
    
    // MARK: -
    
    func updateVcValue() {
        guard let userModel = viewModel.userModel else {
            return
        }
        let avatarUrl = userModel.trueAvatar
        if let url = URL(string: avatarUrl) {
            avatarBtn.kf.setImage(with: url, for: .normal)
        }
        if userId == ARUserManager.shared.userId ?? "" {
            followBtn.isHidden = true
            moreBtn.isHidden = true
        } else {
            moreBtn.isHidden = false
            followBtn.isHidden = userModel.isFollow ?? false
        }
        
        nicknameLabel.text = userModel.nickname
    }

    private func refreshData() {
        self.ar.showLoading()
        viewModel.fetchUser { [weak self] err in
            self?.ar.hideHUD()
            if let err = err {
                self?.ar.makeToast(err.localizedDescription)
                return
            }
            self?.workController.loadData()
            self?.updateVcValue()
        }
    }
    
    // MARK: - Lazy
    
    private lazy var bgView: UIImageView = {
        let imageView = UIImageView(image: .init(named: "personalPage_bg"))
        return imageView
    }()
    
    private lazy var backBtn: UIButton = {
        let btn = UIButton(type: .custom)
        btn.addTarget(self, action: #selector(ar_transitionToBack), for: .touchUpInside)
        btn.setImage(.init(named: "common_nav_new_back_white_icon"), for: .normal)
        return btn
    }()
    
    private lazy var moreBtn: UIButton = {
        let btn = UIButton(type: .custom)
        btn.addTarget(self, action: #selector(moreBtnCliked(_:)), for: .touchUpInside)
        btn.setImage(.init(named: "common_more"), for: .normal)
        return btn
    }()
    
    private lazy var avatarBtn: UIButton = {
        let btn = UIButton(type: .custom)
        btn.layer.cornerRadius = 44
        btn.layer.masksToBounds = true
        btn.layer.borderColor = UIColor.white.cgColor
        btn.layer.borderWidth = 1
        return btn
    }()
    
    private lazy var followBtn: UIButton = {
        let btn = UIButton(type: .custom)
        btn.addTarget(self, action: #selector(followBtnClicked(_:)), for: .touchUpInside)
        btn.setImage(.init(named: "common_follow_icon"), for: .normal)
        btn.isHidden = true
        return btn
    }()
    
    private lazy var nicknameLabel: UILabel = {
        let label = UILabel()
        label.numberOfLines = 1
        label.font = ARHelper.font(16, weight: .medium)
        label.textColor = .init(hexString: "#404040")
        return label
    }()

    private lazy var giftNumView: ARReciveGiftView = {
        let view = ARReciveGiftView(userId: userId)
        return view
    }()
    
    private lazy var workController: ARWorkWaterFlowController = {
        let vc = ARWorkWaterFlowController(viewModel: viewModel)
        vc.setupHeaderRefresherEnable(true)
        vc.waterFlowHeightRatio = [224.0 / 166]
        return vc
    }()
    
}
